const getId = () => {
  const urlArr = window.location.href.split('/')
  return urlArr.pop()
}

const isYapi = () => {
  return window.location.host.includes('yapi')
}
const isInterfaceApi = (url) => {
  return url.startsWith('/api/interface/get')
}

(function() {
  const XHR = XMLHttpRequest.prototype
  const send = XHR.send
  const open = XHR.open
  XHR.open = function(method, url) {
    this._method = method
    this._url = url
    return open.apply(this, arguments)
  }
  XHR.send = function() {
    this.addEventListener('load', function() {
      if (this.responseType !== 'blob' && this.responseText) {
        const res = JSON.parse(this.responseText)
        const data = {
          key: 'chrome_plugin_demo',
          res,
          url: this._url,
          id: getId()
        }
        // 通过 background 作为中转， 将数据传递到 popup 
        if (isYapi() && isInterfaceApi(this._url)) {
          console.log('--xhr load--', this._url, data)
          window.postMessage(data, '*')
        }
      }
    })
    send.apply(this, arguments)
  }
})()
